import "/_content/CommonRcl/Chart.js/chart.umd.min.js";
import "/_content/CommonRcl/Chart.js/chartjs-plugin-annotation.min.js";

// 确保 Chart 对象已定义
if (typeof Chart === 'undefined') {
    console.error('Chart.js is not loaded properly');
}

Chart.defaults.font.size = 16;

export function createMultiLineChart(domCanvas, xLabel, yLabel) {
    if (domCanvas == null)
        return null;
    let chartConfig = {
        type: 'line',
        data: {
            datasets: []
        },
        options: {
            animation: false,
            maintainAspectRatio: false,
            interaction: {
                mode: 'nearest',
                intersect: false
            },
            elements: {
                line: {
                    tension: 0 // 设置为0，显示为直线
                }
            },
            scales: {
                x: {
                    beginAtZero: true,
                    type: 'linear',
                    title: {
                        display: true,
                        text: xLabel
                    }
                },
                y: {
                    beginAtZero: true,
                    type: 'linear',
                    title: {
                        display: true,
                        text: yLabel
                    }
                }
            },
            plugins: { 
                legend: { 
                    display: true,
                    position: 'top',
                    onClick: function(e, legendItem, legend) {
                        // 获取点击的数据集
                        const index = legendItem.datasetIndex;
                        const dataset = legend.chart.data.datasets[index];
                        
                        // 如果设置了点击回调，则调用
                        if (domCanvas.dotNetHelper && dataset) {
                            domCanvas.dotNetHelper.invokeMethodAsync('OnLineClicked', dataset.label);
                        }
                        
                        // 执行默认的图例点击行为（显示/隐藏线段）
                        legend.chart.setDatasetVisibility(index, !legend.chart.isDatasetVisible(index));
                        legend.chart.update();
                    },
                    labels: {
                        generateLabels: function(chart) {
                            const datasets = chart.data.datasets;
                            const labels = Chart.defaults.plugins.legend.labels.generateLabels(chart);
                            
                            // 使用 displayName 替换标签文本
                            for (let i = 0; i < labels.length; i++) {
                                const dataset = datasets[labels[i].datasetIndex];
                                if (dataset && dataset.displayName) {
                                    labels[i].text = dataset.displayName;
                                }
                            }
                            
                            return labels;
                        }
                    }
                },
                tooltip: {
                    callbacks: {
                        title: function(tooltipItems) {
                            return null;
                        },
                        label: function(context) {
                            let label = '';
                            if (context.parsed.y !== null) {
                                label += `(${context.parsed.x.toFixed(2)}, ${context.parsed.y.toFixed(2)})`;
                            }
                            return label;
                        }
                    }
                },
                annotation: {
                    annotations: {
                        // 垂直分隔线的配置将在 updateMultiLineChart 中动态添加
                    }
                }
            }
        }
    };
    let chart = new Chart(domCanvas, chartConfig);
    domCanvas.chart = chart;
    return chart;
}

export function setupLineClickHandler(domCanvas, dotNetHelper) {
    if (!domCanvas || !dotNetHelper)
        return;
        
    // 保存 .NET 对象引用
    domCanvas.dotNetHelper = dotNetHelper;
    
    // 添加画布点击事件处理
    domCanvas.onclick = function(evt) {
        const chart = domCanvas.chart;
        if (!chart) return;
        
        // 获取点击位置的数据点
        const points = chart.getElementsAtEventForMode(evt, 'nearest', { intersect: true }, true);
        
        if (points.length > 0) {
            // 获取点击的数据集和索引
            const firstPoint = points[0];
            const dataset = chart.data.datasets[firstPoint.datasetIndex];
            
            // 调用 .NET 方法
            if (dataset && domCanvas.dotNetHelper) {
                domCanvas.dotNetHelper.invokeMethodAsync('OnLineClicked', dataset.label);
            }
        }
    };
}

export function updateMultiLineChart(domCanvas, datasetsJson, verticalLineX) {
    let chart = domCanvas?.chart;
    if (chart == null)
        return;
    
    // 解析数据集
    const datasets = JSON.parse(datasetsJson);
    
    // 更新图表数据
    chart.data.datasets = datasets;
    
    // 设置垂直分隔线
    if (verticalLineX !== null && verticalLineX !== undefined) {
        // 创建垂直线注释
        chart.options.plugins.annotation.annotations = {
            gearShiftLine: {
                type: 'line',
                xMin: verticalLineX,
                xMax: verticalLineX,
                borderColor: 'red',
                borderWidth: 2,
                borderDash: [5, 5],
                label: {
                    display: true,
                    content: 'L/H',
                    position: 'start',
                    backgroundColor: 'rgba(255, 0, 0, 0.7)',
                    color: 'white',
                    font: {
                        size: 12
                    }
                }
            }
        };
    } else {
        // 如果没有设置垂直线，则清除注释
        chart.options.plugins.annotation.annotations = {};
    }
    
    // 更新图表
    chart.update();
} 